﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recRestructurhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;

using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;
using System.Web.SessionState;

namespace SIPO.Web.AjaxHandler.Transaction {
    public class recRestructurhandler : SIPO.Web.BaseHandler, IRequiresSessionState
    {
        private recRestructurRepo repo =
            new recRestructurRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recTransactionTypeRepo TransTypeDal =
           new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recRestructurDetailRepo repdet = new recRestructurDetailRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recDemandRepo repoDemand =
            new recDemandRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recBillingRepo BillingDal = new recBillingRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("getdetailbyresid"):
                    context.Response.Write(GetDetailByResId(context));
                    break;
                case ("getdetailbydebtid"):
                    context.Response.Write(GetTransBilByDebtID(context));
                    break;
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                //bind data ke session dari input restrukturisasi
                case ("inserttosession"):
                    InsertToSession(context);
                    break;
                //untuk event dropdownlist Debitur onchange (populate data recDemandDetail) (recRestructurform.aspx)
                case ("gettransbydebtid"):
                    context.Response.Write(GetTransBilByDebtID(context));
                    break;    
                //untuk bind data di grid Restrukturisasi (recRestructurlist.aspx)
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                //untuk input schema pembayaran (recRestructurNextform.aspx)
                case ("getdummygrid"):
                    context.Response.Write(GetDummyGrid(context));
                    break;
                //untuk load schemaOnly (recRestructurNextform.aspx)
                case ("getschedforview"):
                    context.Response.Write(GetSchedForView(context));
                    break;    
                default:
                    // do nothing
                    break;
            }
        }

        private string GetSchedForView(HttpContext context)
        {
            List<recRestructurSchedule> grid = new List<recRestructurSchedule>();

            if (context.Session["resschema"] != null)
            {
                grid = (List<recRestructurSchedule>)context.Session["resschema"];
            }

            var gridData = new
            {
                page = 1,
                total = 10,
                records = grid.Count,
                rows = grid
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }
        private string GetDummyGrid(HttpContext context) {
            List<recRestructurSchedule> grid = new List<recRestructurSchedule>();
            int maxRow = 1;
            int Value = 0;
            if (context.Request.Params["rowcount"] != null) {
                if (!context.Request.Params["rowcount"].ToString().Trim().Equals(""))
                    maxRow = int.Parse(context.Request.Params["rowcount"].ToString());
            }
            if (context.Request.Params["val"] != null)
            {
                if (!context.Request.Params["val"].ToString().Trim().Equals(""))
                    Value = int.Parse(context.Request.Params["val"].ToString().Replace(".", "").Replace(",00",""));
            }
            
            int val=0;
            if (maxRow == 1)
                val = Value;
            else
            {
                val = Value / maxRow;
                int jo = int.Parse(val.ToString().Substring(0,1));
                string nol = string.Empty;
                try
                {
                     jo = int.Parse(val.ToString().Substring(0, val.ToString().Length % 3));
                }
                catch
                {
                    //do nothing
                }
                    for (int a = 0; a < val.ToString().Length - jo.ToString().Length; a++)
                    {
                        nol += "0";
                    }
                    val = int.Parse(jo + nol);

            }
           
          
            for (int i = 1; i <= maxRow; i++) {
                recRestructurSchedule obj = new recRestructurSchedule();
                obj.ScheduleTime = i.ToString();
                if (i == maxRow)
                {
                    obj.PaymentValue =  val +(Value-val*i);
                }
                else
                {
                    obj.PaymentValue = val;
                }
                
                    //obj.CreatedDate = DateTime.Now;
                //obj.CreatedBy = base.UserLoggedIn;
                grid.Add(obj);
            }
            
            var gridData = new
            {
                page = 1,
                total = 10,
                records = grid.Count,
                rows = grid
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string GetTransByDebtID(HttpContext context) {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = recDemandDetail.Fields.DemandDetailNo;
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            
            List<recDemandDetail> pagedList = null;
            List<recRestructurDetailDTO> recRestructurDetailDTOs = null;

            string debtID = context.Request.QueryString["debtid"].ToString();
            string ResID  = context.Request.Params["ResID"];
            
            if (debtID == null || debtID == "" || debtID == string.Empty) return "";

            try
            {
                totalCount = Convert.ToInt32(repoDemand.SelectScalarDemandDetailByDebtorID(SQL.Function.Aggregate.Count,
                    "DemandDetailNo",
                    parameters,
                    debtID));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = repoDemand.GetListDemandDetailByDebtorID(pageSize, page, sidx, sord, parameters, debtID);

                int a = pagedList.Count;
                //try
                //{
                    for (int al = 0; al < a;al++ )
                    {

                        List<recDemandDetail> list = pagedList.FindAll(x => x.DemandNo == pagedList[al].DemandNo);
                        if (list.Count > 1)
                        {
                            int i = 0;
                            foreach (recDemandDetail dtoi in list)
                            {
                                i++;
                                if (i != list.Count)
                                {
                                    pagedList.Remove(dtoi);
                                    al++;
                                }

                            }
                        }
                    }
                //}
                //catch { 
                ////do nothing
                //}
                recRestructurDetailDTOs =
                   pagedList.Select(x => new recRestructurDetailDTO
                   {
                       DemandDetailID = x.DemandDetailNo,
                       IDTransaksi = x.TransNo,
                       JenisPungutan = x.TransName,
                       Nilai = x.TransValue,
                       NoSanksi = x.SanctionNo
                   }).ToList<recRestructurDetailDTO>();
                
                if (ResID != null && ResID != "")
                {
                    List<recRestructurDetail> list = repo.GetDetailListByResID(int.Parse(ResID));
                    if (list != null)
                    {
                        foreach (recRestructurDetail res in list)
                        {
                            recRestructurDetailDTO resdet = recRestructurDetailDTOs.Find(x => x.IDTransaksi == res.TransDemandNo); // cek di res gue ada gak
                            if (resdet == null) // kalo ga ada , ni ada yang punya ga
                            {
                                recRestructurDetail det = repdet.GetList().Find(x => x.TransDemandNo == resdet.IDTransaksi); //jika ada hapus dari list
                                if(det!=null)
                                recRestructurDetailDTOs.Remove(resdet);
                            }
                            }
                    }
                }

            
             
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetTransByDebtID";
                log.LogMessage = ex.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = 1,
                records = recRestructurDetailDTOs.Count,
                rows = recRestructurDetailDTOs
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        private string GetTransBilByDebtID(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = recBilling.Fields.BillingNo;
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            //int totalCount = 0;
            //int totalPages = 0;

            List<recBilling> pagedList = null;
            //List<recRestructurDetailDTO> recRestructurDetailDTOs = null;

            string debtID = context.Request.QueryString["debtid"].ToString();
            string ResID = context.Request.Params["ResID"];

            if (debtID == null || debtID == "" || debtID == string.Empty) return "";

            try
            {
                //totalCount = Convert.ToInt32(repoDemand.SelectScalarDemandDetailByDebtorID(SQL.Function.Aggregate.Count,
                //    "DemandDetailNo",
                //    parameters,
                //    debtID));

                //decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                //totalPages = Convert.ToInt32(dc);
                //if (ResID != null && ResID != "") {
                //    pagedList = BillingDal.GetListByDebtorEdit(debtID,ResID);
                //}
                //else{
                    pagedList = BillingDal.GetListByDebtorAdd(debtID);
                //}
                int a = pagedList.Count;
                //try
                //{
                //for (int al = 0; al < a; al++)
                //{

                //    List<recBilling> list = pagedList.FindAll(x => x.BillingNo == pagedList[al].BillingNo);
                //    if (list.Count > 1)
                //    {
                //        int i = 0;
                //        foreach (recBilling dtoi in list)
                //        {
                //            i++;
                //            if (i != list.Count)
                //            {
                //                pagedList.Remove(dtoi);
                //                al++;
                //            }

                //        }
                //    }
                //}
                ////}
                //catch { 
                ////do nothing
                //}
                //recRestructurDetailDTOs =
                //   pagedList.Select(x => new recRestructurDetailDTO
                //   {
                //       DemandDetailID = x.BillingNo,
                //       IDTransaksi = x.BillingNo,
                //       JenisPungutan = x.TransName,
                //       Nilai = x.Value,
                //       NoSanksi = x.InvoiceNo
                //   }).ToList<recRestructurDetailDTO>();

                //if (ResID != null && ResID != "")
                //{
                //    List<recRestructurDetail> list = repo.GetDetailListByResID(int.Parse(ResID));
                //    if (list != null)
                //    {
                //        foreach (recRestructurDetail res in list)
                //        {
                //            recRestructurDetailDTO resdet = recRestructurDetailDTOs.Find(x => x.IDTransaksi == res.TransDemandNo); // cek di res gue ada gak
                //            if (resdet == null) // kalo ga ada , ni ada yang punya ga
                //            {
                //                recRestructurDetail det = repdet.GetList().Find(x => x.TransDemandNo == resdet.IDTransaksi); //jika ada hapus dari list
                //                if (det != null)
                //                    recRestructurDetailDTOs.Remove(resdet);
                //            }
                //        }
                //    }
                //}

                 

            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetTransByDebtID";
                log.LogMessage = ex.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = 1,
                total = 1,
                records = pagedList.Count,
                rows = pagedList
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }
        
        
        private void InsertToSession(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                string debtId = string.Empty;
                if (context.Request.Params["ddlDebtor"] != null)
                    debtId = context.Request.Params["ddlDebtor"].ToString().Trim();
                //if (context.Request.Params["InvoiceNo"] != null)
                    string invoice = context.Request.Params["InvoiceNo"].ToString().Trim();
                
                var strId = (string)context.Request.Params["iddetail"].ToString().Trim();
                string[] ids = strId.Split(',');
                
                List<recBilling> listDemDet = BillingDal.GetListByDebtorAdd(invoice)
                    .Where(x => ids.Contains(x.BillingNo.ToString())).ToList<recBilling>();
                    
                recRestructur res = new recRestructur();
                res.DebtorID = int.Parse(debtId);

                recDebtorRepo repoDebtor = new recDebtorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                res.DebtorName = repoDebtor.GetById(int.Parse(debtId)).DebtorName;
                repoDebtor = null;
                //string a = context.Request.Params["txtTglSK"].ToString().Trim().Replace("%252F", "");
                //a = a.ToString().Trim().Replace("%2F", "");
                //a = a.Substring(4, 4) +"-"+ a.Substring(2, 2) +"-"+ a.Substring(0, 2);
                res.ActionRestructurName = context.Request.Params["keputusan"] == null ? "" : context.Request.Params["Keputusan"].ToString().Replace("%20"," ");
                res.LetterNo = context.Request.Params["txtNoSK"] == null ? "" : context.Request.Params["txtNoSK"].ToString().Trim();
                res.RestructurID = context.Request.Params["hfID"] == "" ? -1 : int.Parse(context.Request.Params["hfID"].ToString().Trim());
                res.InvoiceNo = invoice;
                try
                {
                    res.LetterDate = context.Request.Params["txtTglSK"] == null ? (DateTime?)null : DateTime.Parse(context.Request.Params["txtTglSK"].ToString());
                }
                catch {
                    string a = context.Request.Params["txtTglSK"].ToString().Trim().Replace("%252F", "");
                    a = a.ToString().Trim().Replace("%2F", "");
                    a = a.Substring(4, 4) + "-" + a.Substring(2, 2) + "-" + a.Substring(0, 2);
                    res.LetterDate = context.Request.Params["txtTglSK"] == null ? (DateTime?)null : DateTime.Parse(a);
               
                }
                    res.SumValues = context.Request.Params["txtJmlTagihan"] == null ? (decimal?)null : decimal.Parse(String.Format("{0:0.00}", context.Request.Params["txtJmlTagihan"].ToString().Trim()
                    .Replace(".", "")
                    .Replace(",", "."))); 
                res.ActionRestructurID = context.Request.Params["ddlJenisRes"] == null ? "" : context.Request.Params["ddlJenisRes"].ToString().Trim();
                if (context.Request.Files.Count > 0)
                {
                    res.LetterNo = res.LetterNo.Replace("%2F", "/");
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string FileName = string.Empty;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;
                    }

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    res.AttachFile = datas;
                    res.AttachFileName = FileName;

                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }
                //Table ga ada ID
                //recActionRestructurRepo repoAct = new recActionRestructurRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                //res.ActionRestructurName = repoAct.GetById(int.Parse(res.ActionRestructurID)).ActionRestructurName;
                //repoAct = null;

                res.RestructurValues = context.Request.Params["txtJmlRestruktur"] == null ? (decimal?)null :
                decimal.Parse(String.Format("{0:0.00}", context.Request.Params["txtJmlRestruktur"].ToString()
                    .Trim()
                    .Replace(".", "")
                    .Replace(",", ".")));

                res.IsActive = true;
                res.CreatedDate = DateTime.Now;
                res.CreatedBy = base.UserLoggedIn;

                List<recRestructurDetail> listResDet = new List<recRestructurDetail>();
                foreach (recBilling det in listDemDet) {
                    recRestructurDetail rr = new recRestructurDetail();
                   // rr.SanctionNo = det.SanctionNo;
                    rr.TransDemandNo = det.BillingNo;
                    rr.TransTypeName = TransTypeDal.GetById(det.TransTypeID).TransTypeName;
                    rr.TransValues = det.Value;

                    rr.TransNo = repo.GetTransNo(det.TransTypeID.ToString());
                    rr.TransTypeID = det.TransTypeID.ToString();
                    
                    rr.CreatedBy = base.UserLoggedIn;
                    rr.CreatedDate = DateTime.Now;
                    
                    listResDet.Add(rr);
                }

                res.recRestructurDetails = listResDet;

                if (context.Session["restructur"] != null) context.Session["restructur"] = null;
                context.Session["restructur"] = res;

                helper.Message = "";
                helper.IsSuccess = true;
                //helper.Data = obj.InvoiceNo;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "InsertToSession";
                log.LogMessage = helper.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

          //  return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }
        private string Insert(HttpContext context)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            
            jsonString = "{\"Schedules\":" + jsonString + "}";
            System.Web.Script.Serialization.JavaScriptSerializer serializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            recRestructurScheduleCollection resSched = serializer.Deserialize<recRestructurScheduleCollection>(jsonString);

            sr.Close();
            sr.Dispose();
            
            recRestructur res = null;
            
            if(context.Session["restructur"]!=null)
                res = (recRestructur)context.Session["restructur"];
                
            string schedType = string.Empty;
            if (context.Request.Params["sched"] != null)
                schedType = context.Request.Params["sched"].ToString();

            int? schedPayment = (int?)null;
            try
            {
                if (context.Request.Params["multi"] != "")
                    schedPayment = int.Parse(context.Request.Params["multi"].ToString());
            }
            catch { 
            //donothing
            }
            try
            {
                res.SchedulePayment = schedPayment;
            }
            catch {
                res.SchedulePayment = null;
            }
                res.ScheduleTypeName = schedType;
            
            JSONHelper helper = new JSONHelper();

            try
            {
                recRestructurRepo repo = 
                    new recRestructurRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                recRestructurDetailRepo repoDetail = 
                    new recRestructurDetailRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                recRestructurScheduleRepo repoSched =
                    new recRestructurScheduleRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

                //save parent
                int lastId = repo.SaveReturnedID(res);

                if (lastId < 0) throw new Exception("Insert failed!");

                foreach (recRestructurDetail det in res.recRestructurDetails) {
                    det.RestructurID = lastId;
                }
                //save detail
                repoDetail.Save(res.recRestructurDetails);

                List<recRestructurSchedule> lsSched = new List<recRestructurSchedule>();
                foreach (recRestructurScheduleDTO det in resSched.Schedules) {
                    recRestructurSchedule ss = new recRestructurSchedule();
                    ss.RestructurID = lastId;
                    ss.PaymentValue = decimal.Parse(det.PaymentValue.ToString().Replace(".00", ""));
                    ss.ScheduleTime = det.ScheduleTime;
                    ss.ScheduleNote = det.ScheduleNote;
                    ss.DueDate = DateTime.Parse(det.DueDate);
                    ss.CreatedBy = base.UserLoggedIn;
                    ss.CreatedDate = DateTime.Now;

                    lsSched.Add(ss);
                }
                //save schedule
                repoSched.Save(lsSched);
               
                
                int b = repo.UpdateIsRestructur(lastId);
                if (b < 0) throw new Exception("Insert failed!");
                
                helper.Message = "Data berhasil disimpan !";
                helper.IsSuccess = true;
                helper.Data = "";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string Update(HttpContext context)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());

            jsonString = "{\"Schedules\":" + jsonString + "}";
            System.Web.Script.Serialization.JavaScriptSerializer serializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            recRestructurScheduleCollection resSched = serializer.Deserialize<recRestructurScheduleCollection>(jsonString);

            sr.Close();
            sr.Dispose();

            recRestructur res = null;

            if (context.Session["restructur"] != null)
                res = (recRestructur)context.Session["restructur"];

            string schedType = string.Empty;
            if (context.Request.Params["sched"] != null)
                schedType = context.Request.Params["sched"].ToString();

            int? schedPayment = (int?)null;
            try
            {
                if (context.Request.Params["multi"] != "" && context.Request.Params["multi"] != null)
                    schedPayment = int.Parse(context.Request.Params["multi"].ToString());
            }
            catch
            { 
            //do nothing
            }
            res.SchedulePayment = schedPayment;
            res.ScheduleTypeName = schedType;

            JSONHelper helper = new JSONHelper();

            try
            {
                recRestructurRepo repo =
                    new recRestructurRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                recRestructurDetailRepo repoDetail =
                    new recRestructurDetailRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                recRestructurScheduleRepo repoSched =
                    new recRestructurScheduleRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

                //save parent
                bool lastId;
                if(res.AttachFile!=null)
                        lastId = repo.Update(res);
                else
                    lastId = repo.UpdateWithoutFile(res);
                
                if (lastId == false) throw new Exception("Update failed!");

                int c = repo.RollBackIsRestructur(res.RestructurID);
                if (c < 0) throw new Exception("Isrestructur failed!");
                repo.DeleteDetByRes(res.RestructurID);
                foreach (recRestructurDetail det in res.recRestructurDetails)
                {
                  //(delete detail RESID)
                   det.RestructurID = res.RestructurID;
                   repoDetail.Save(det);
                }
                
                

                List<recRestructurSchedule> lsSched = new List<recRestructurSchedule>();
                repo.DeleteSchedByRes(res.RestructurID);
                foreach (recRestructurScheduleDTO det in resSched.Schedules)
                {
                    //(delete schedule RESID)
                    recRestructurSchedule ss = new recRestructurSchedule();
                    ss.RestructurID = res.RestructurID;
                    ss.PaymentValue = decimal.Parse(det.PaymentValue.ToString().Replace(".00",""));
                    ss.ScheduleTime = det.ScheduleTime;
                    ss.ScheduleNote = det.ScheduleNote;
                    ss.DueDate = DateTime.Parse(det.DueDate);
                    ss.CreatedBy = base.UserLoggedIn;
                    ss.CreatedDate = DateTime.Now;
                    repoSched.Save(ss);
                   
                }
              
                int b = repo.UpdateIsRestructur(res.RestructurID);
                if (b < 0) throw new Exception("Isrestrustur failed!");
               

                helper.Message = "Data berhasil disimpan !";
                helper.IsSuccess = true;
                helper.Data = "";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recRestructur.Fields.RestructurID : context.Request.QueryString["sidx"].ToString());
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recRestructur> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(repo.SelectScalar(SQL.Function.Aggregate.Count, "recRestructur.RestructurID", parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = repo.GetListFullObject(pageSize, page, sidx, sord, parameters);
                context.Session["punyaseno"] = pagedList;    
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recRestructurhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }
        public string GetDetailByResId(HttpContext context)
        {
            int ResID = 0;
            int.TryParse(context.Request.Params["ResID"], out ResID);

            List<recRestructurDetail> list = repo.GetDetailListByResID(ResID);

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }
        public string GetDetailByDebtId(HttpContext context)
        {
            int DebtID = 0;
            int.TryParse(context.Request.Params["debtID"], out DebtID);

            List<recRestructurDetail> list = repo.GetDetailListByDebtId(DebtID);

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }

    }
}
